using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using SJVars;
using SJXmlP.XMLClasses;
using Spacejock;
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Windows.Forms;
using yW5Lib;
using yWriter6.My.Resources;

namespace yWriter6
{
	public class clsExportRTFToLaTeX
	{
		private Collection colTex;

		private const string OpenTex = "<TEX>";

		private const string CloseTex = "</TEX>";

		private const string TexInlineStart = "<TEX ";

		private const string TexInlineEnd = " /TEX>";

		private const string EOLMarker = "[EOL!$]";

		private clsRTF cRTF;

		public clsExportRTFToLaTeX()
		{
			colTex = new Collection();
			cRTF = new clsRTF(ref clsShared.cLog, ref clsShared.cSettings);
		}

		public void Export(clsProject cProject, bool AskWhichChapters)
		{
			//Discarded unreachable code: IL_0974, IL_098e, IL_099c, IL_09ac, IL_0c1e, IL_0c20, IL_0c34, IL_0c56
			int num = default(int);
			int num3 = default(int);
			try
			{
				ProjectData.ClearProjectError();
				num = 2;
				int num2 = 2;
				StringBuilder SB = new StringBuilder();
				num2 = 3;
				string TextString = "";
				num2 = 4;
				clsCollection<int> clsCollection = new clsCollection<int>();
				num2 = 5;
				RichTextBox richTextBox = new RichTextBox();
				num2 = 6;
				bool latexSingleQuotes = cProject.LatexSingleQuotes;
				num2 = 7;
				clsShared.cSettings.sGet("EditorFontName", "Segoe UI");
				num2 = 8;
				clsShared.cSettings.sGet("EditorFontSize", 10f);
				num2 = 9;
				string text = cProject.LatexHeaderFile;
				num2 = 10;
				if (Operators.CompareString(text, "", TextCompare: false) == 0)
				{
					num2 = 11;
					text = "LaTeXDefaultHeader.txt";
				}
				num2 = 12;
				if (!text.Contains(Conversions.ToString(Path.DirectorySeparatorChar)))
				{
					num2 = 13;
					text = Path.Combine(cProject.ProjectPath(), text);
				}
				num2 = 14;
				if (!clsShared.cFile.FileExists(text))
				{
					num2 = 15;
					clsShared.cLog.AddAction(text + " not found.");
					num2 = 16;
					clsShared.cLog.AddAction("Using default LaTeX header");
					num2 = 17;
					TextString = Resources.LatexHeader;
				}
				else
				{
					num2 = 19;
					clsShared.cLog.AddAction("Using LaTeX header file " + text);
					num2 = 20;
					clsShared.cFile.ReadTextAuto(text, ref TextString, UseSysEncoding: true);
				}
				num2 = 21;
				string str = clsShared.cFile.FileWithoutExt(cProject.FileWithPath);
				num2 = 22;
				str += ".tex";
				num2 = 23;
				if (Operators.CompareString(str, "", TextCompare: false) != 0)
				{
					num2 = 24;
					if (!AskWhichChapters)
					{
						num2 = 25;
						clsCollection = cProject.AllChapterIDs();
						goto IL_024c;
					}
					num2 = 27;
					frmPickChapters frmPickChapters = new frmPickChapters(ref cProject);
					num2 = 28;
					frmPickChapters.HidePrinterSelect();
					num2 = 29;
					frmPickChapters.HideTagFilter();
					num2 = 30;
					frmPickChapters.HideVPFilter();
					num2 = 31;
					frmPickChapters.ShowDialog();
					num2 = 32;
					if (!frmPickChapters.Cancelled)
					{
						num2 = 34;
						clsCollection = frmPickChapters.PickedIDs;
						num2 = 35;
						str = frmPickChapters.PickedFilename;
						num2 = 36;
						if (Operators.CompareString(str, "", TextCompare: false) == 0)
						{
							num2 = 37;
							str = Path.Combine(cProject.ProjectPath(), clsShared.cFile.FileOnly(clsShared.cFile.FileWithoutExt(cProject.FileWithPath)) + ".tex");
						}
						else
						{
							num2 = 39;
							str = Path.Combine(cProject.ProjectPath(), str + ".tex");
						}
						goto IL_024c;
					}
				}
				goto end_IL_0000;
				IL_024c:
				num2 = 40;
				string[] array = Strings.Split(TextString, "\r\n");
				num2 = 41;
				string[] array2 = array;
				foreach (string text2 in array2)
				{
					num2 = 42;
					if (Operators.CompareString(text2.Trim(), "", TextCompare: false) != 0)
					{
						num2 = 43;
						SB.AppendLine(text2);
					}
					num2 = 44;
				}
				num2 = 45;
				SB.AppendLine("\\author{" + cProject.AuthorName + "}");
				num2 = 46;
				SB.AppendLine("\\title{" + cProject.Title + "}");
				num2 = 47;
				SB.AppendLine("\\begin{document}");
				num2 = 48;
				SB.AppendLine("\\frontmatter");
				num2 = 49;
				bool latexSuppressChapterTitles = cProject.LatexSuppressChapterTitles;
				num2 = 50;
				bool flag = false;
				num2 = 51;
				bool flag2 = false;
				num2 = 52;
				IEnumerator enumerator = cProject.Chapters.GetEnumerator();
				bool flag3 = default(bool);
				while (enumerator.MoveNext())
				{
					clsChapter clsChapter = (clsChapter)enumerator.Current;
					num2 = 53;
					if (clsCollection.Contains(clsChapter.ID))
					{
						num2 = 54;
						if ((cProject.EndFrontmatterChID == 0) | !cProject.Chapters.IDUsed(cProject.EndFrontmatterChID))
						{
							num2 = 55;
							SB.AppendLine("\\mainmatter");
							num2 = 56;
							SB.AppendLine("\\pagestyle{plain}");
							num2 = 57;
							flag3 = true;
						}
						num2 = 58;
						bool flag4;
						if (clsChapter.Title.StartsWith("@"))
						{
							num2 = 59;
							flag4 = true;
						}
						else
						{
							num2 = 61;
							flag4 = false;
						}
						num2 = 62;
						if (!clsChapter.Unused)
						{
							num2 = 63;
							if (!IsEmptyChapter(cProject, clsChapter))
							{
								num2 = 64;
								if (flag3 & (clsChapter.Type == ChapterTypes.ChapterNormal))
								{
									num2 = 65;
									if (!flag4)
									{
										num2 = 66;
										if (latexSuppressChapterTitles)
										{
											num2 = 67;
											SB.AppendLine("\\chapter{}");
										}
										else
										{
											num2 = 69;
											SB.AppendLine("\\chapter{" + clsChapter.Title + "}");
										}
									}
									else
									{
										num2 = 71;
										if (flag4 & clsChapter.Title.Contains("Chapter"))
										{
											num2 = 72;
											SB.AppendLine("\\chapter{}");
										}
										else
										{
											num2 = 74;
											SB.AppendLine("\\newpage");
										}
									}
								}
								num2 = 75;
								flag = false;
								num2 = 76;
								flag2 = false;
								num2 = 77;
								int sceneCount = clsChapter.SceneCount;
								for (int j = 1; j <= sceneCount; j++)
								{
									num2 = 78;
									int iD = clsChapter.get_SceneIDByIndex(j);
									num2 = 79;
									clsScene clsScene = cProject.get_SceneByID(iD);
									num2 = 80;
									if (!clsScene.Unused)
									{
										num2 = 81;
										if (flag3)
										{
											num2 = 82;
											if (flag)
											{
												num2 = 83;
												if (!clsScene.AppendToPrevious)
												{
													num2 = 84;
													flag2 = true;
												}
											}
										}
										num2 = 85;
										string RTF = modSubs.RTFWithParsedVars(cProject, clsScene, modVariables.eFinalExportType.Latex);
										num2 = 86;
										richTextBox.Rtf = RTF;
										num2 = 87;
										string text3 = richTextBox.Text;
										num2 = 88;
										if (text3.StartsWith("<TEX>"))
										{
											num2 = 89;
											flag = true;
											num2 = 90;
											if (!flag3)
											{
												num2 = 91;
												SB.AppendLine("\\newpage");
											}
											else
											{
												num2 = 93;
												if (flag2)
												{
													num2 = 94;
													AddSceneSeparator(cProject.LatexSceneDividerStyle, ref SB);
												}
											}
											num2 = 95;
											text3 = Strings.Mid(text3, Strings.Len("<TEX>") + 1);
											num2 = 96;
											text3 = Strings.Replace(text3, Conversions.ToString(Strings.Chr(169)), "\\copyright");
											num2 = 97;
											SB.AppendLine(text3);
										}
										else
										{
											num2 = 99;
											if (text3.ToLower().StartsWith("<html>"))
											{
												num2 = 100;
												flag = false;
											}
											else
											{
												num2 = 102;
												if (clsScene.ExportCondSpecific & !clsScene.ExportWhenLaTeX)
												{
													num2 = 103;
													flag = false;
												}
												else
												{
													num2 = 105;
													flag = true;
													num2 = 106;
													if (!flag3)
													{
														num2 = 107;
														SB.AppendLine("\\newpage");
													}
													else
													{
														num2 = 109;
														if (flag2)
														{
															num2 = 110;
															AddSceneSeparator(cProject.LatexSceneDividerStyle, ref SB);
														}
													}
													num2 = 111;
													PreserveTex(ref RTF);
													num2 = 112;
													RTF = NewCleanRTF(RTF);
													num2 = 113;
													ParseTex(ref RTF);
													num2 = 114;
													clsShared.cHtml.StripBetweenTags(ref RTF, "<htm", "/htm>");
													num2 = 115;
													clsShared.cHtml.StripBetweenTags(ref RTF, "<HTM", "/HTM>");
													num2 = 116;
													clsShared.cHtml.StripBetweenTags(ref RTF, "<RTF", "/RTF>");
													num2 = 117;
													clsShared.cHtml.StripBetweenTags(ref RTF, "<rtf", "/rtf>");
													num2 = 118;
													clsShared.cHtml.StripBetweenTags(ref RTF, "<rtf img", "/img>");
													num2 = 119;
													clsShared.cHtml.StripBetweenTags(ref RTF, "<rtf url", "/url>");
													num2 = 120;
													clsShared.cHtml.StripBetweenTags(ref RTF, "[epub_", "]");
													num2 = 121;
													clsShared.cHtml.StripBetweenTags(ref RTF, "[mobi_", "]");
													num2 = 122;
													string[] array3 = Strings.Split(RTF, "\n");
													num2 = 123;
													string[] array4 = array3;
													for (int k = 0; k < array4.Length; k = checked(k + 1))
													{
														string text4 = array4[k];
														num2 = 124;
														if (Operators.CompareString(text4.Trim(), "", TextCompare: false) != 0)
														{
															num2 = 125;
															if (text4.Contains("\""))
															{
																num2 = 126;
																text4 = clsShared.cText.ReplaceAlternatingMarkers(text4, "\"", "``", "''");
																num2 = 127;
																text4 = Strings.Replace(text4, "`` ", "``");
																num2 = 128;
																if (latexSingleQuotes)
																{
																	num2 = 129;
																	text4 = Strings.Replace(text4, "``", "`");
																	num2 = 130;
																	text4 = Strings.Replace(text4, "''", "'");
																}
															}
															num2 = 131;
															text4 = Strings.Replace(text4, "Mr. ", "Mr.\\ ");
															num2 = 132;
															text4 = Strings.Replace(text4, "Mrs. ", "Mrs.\\ ");
															num2 = 133;
															text4 = Strings.Replace(text4, "Dr. ", "Dr.\\ ");
															num2 = 134;
															text4 = Strings.Replace(text4, "Ms. ", "Ms.\\ ");
															num2 = 135;
															if (text4.EndsWith("[EOL!$]\r"))
															{
																num2 = 136;
																SB.AppendLine(Strings.Replace(text4, "[EOL!$]", ""));
															}
															else
															{
																num2 = 138;
																SB.AppendLine(text4 + "\\par");
															}
														}
														num2 = 139;
													}
												}
											}
										}
									}
									num2 = 140;
								}
							}
						}
					}
					num2 = 141;
					if (clsChapter.ID == cProject.EndFrontmatterChID)
					{
						num2 = 142;
						SB.AppendLine("\\mainmatter");
						num2 = 143;
						SB.AppendLine("\\pagestyle{plain}");
						num2 = 144;
						flag3 = true;
					}
					num2 = 145;
				}
				num2 = 146;
				if (enumerator is IDisposable)
				{
					(enumerator as IDisposable).Dispose();
				}
				num2 = 147;
				SB.AppendLine("\\end{document}");
				num2 = 148;
				clsShared.cFile.WriteTextFile(str, SB.ToString());
				num2 = 149;
				clsShared.cFile.RunFile(cProject.ProjectPath());
				end_IL_0000:;
			}
			catch (Exception obj) when ((obj != null && num != 0) & (num3 == 0))
			{
				ProjectData.SetProjectError(obj);
				/*Error near IL_0c54: Could not find block for branch target IL_0c20*/;
			}
			if (num3 != 0)
			{
				ProjectData.ClearProjectError();
			}
		}

		private void AddSceneSeparator(int SceneDividerStyle, ref StringBuilder SB)
		{
			SB.AppendLine("\\setsubsecheadstyle{\\bfseries\\centering}");
			switch (SceneDividerStyle)
			{
			case 0:
				SB.AppendLine("\\subsection*{ }");
				break;
			case 1:
				SB.AppendLine("\\subsection*{*}");
				break;
			case 2:
				SB.AppendLine("\\subsection*{* * *}");
				break;
			case 3:
				SB.AppendLine("\\subsection*{\\#}");
				break;
			}
		}

		private string NewCleanRTF(string RTF)
		{
			string text = "";
			try
			{
				text = cRTF.RTFToMarkup(RTF);
				text = clsShared.cText.RemoveDblSpaces(text);
				text = text.Trim();
				text = Strings.Replace(text, "$", "\\$");
				text = Strings.Replace(text, "&", "\\&");
				text = Strings.Replace(text, "#", "\\#");
				text = Strings.Replace(text, "%", "\\%");
				text = Strings.Replace(text, "_", "\\_");
				text = Strings.Replace(text, "{", "\\{");
				text = Strings.Replace(text, "}", "\\}");
				text = Strings.Replace(text, Conversions.ToString(Strings.Chr(145)), "\\" + Conversions.ToString(Strings.Chr(145)));
				text = Strings.Replace(text, Conversions.ToString(Strings.Chr(146)), "\\" + Conversions.ToString(Strings.Chr(146)));
				text = Strings.Replace(text, Conversions.ToString(Strings.Chr(147)), "\\" + Conversions.ToString(Strings.Chr(147)));
				text = Strings.Replace(text, Conversions.ToString(Strings.Chr(148)), "\\" + Conversions.ToString(Strings.Chr(148)));
				text = Strings.Replace(text, "«", "\\og ");
				text = Strings.Replace(text, "»", "\\fg{} ");
				text = Strings.Replace(text, "ç", "\\c ");
				text = Strings.Replace(text, "Œ", "\\OE ");
				text = Strings.Replace(text, "œ", "\\oe ");
				text = Strings.Replace(text, "ï", "\\\"i ");
				text = Strings.Replace(text, "...", "\\ldots");
				ConvertMarkupFormatting(ref text, "[i]", "[/i]", "\\emph{", "}");
				ConvertMarkupFormatting(ref text, "[b]", "[/b]", "\\textbf{", "}");
				ConvertMarkupFormatting(ref text, "[u]", "[/u]", "\\underline{", "}");
				ConvertMarkupFormatting(ref text, "[s]", "[/s]", "\\sout{", "}");
				text = Strings.Replace(text, "[h]", "", 1, -1, CompareMethod.Text);
				text = Strings.Replace(text, "[/h]", "", 1, -1, CompareMethod.Text);
				text = Strings.Replace(text, "[h1]", "", 1, -1, CompareMethod.Text);
				text = Strings.Replace(text, "[/h1]", "", 1, -1, CompareMethod.Text);
				ConvertMarkupFormatting(ref text, "[l]", "[/l]", "\\raggedright{", "}");
				ConvertMarkupFormatting(ref text, "[r]", "[/r]", "\\raggedleft{", "}");
				ConvertMarkupFormatting(ref text, "[c]", "[/c]", "\\centering{", "}");
				do
				{
					text = Strings.Replace(text, "\r\n}", "}\r\n");
				}
				while (Strings.InStr(text, "\r\n}") != 0);
				do
				{
					text = Strings.Replace(text, "\n}", "}\r\n");
				}
				while (Strings.InStr(text, "\n}") != 0);
				text = Strings.Replace(text, "} ,", "},");
				text = Strings.Replace(text, "} ?", "}?");
				text = Strings.Replace(text, "} '", "}'");
				text = Strings.Replace(text, "} !", "}!");
				text = Strings.Replace(text, "} .", "}.");
				return Strings.Replace(text, "} ;", "};");
			}
			catch (Exception ex)
			{
				ProjectData.SetProjectError(ex);
				Exception ex2 = ex;
				ProjectData.ClearProjectError();
				return RTF;
			}
		}

		private void ConvertMarkupFormatting(ref string Markup, string OpenTag, string CloseTag, string NewOpenTag, string NewCloseTag)
		{
			clsShared.cText.ReplaceWithinBlocks(ref Markup, OpenTag, CloseTag, "\r\n", CloseTag + "\r\n" + OpenTag);
			Markup = Strings.Replace(Markup, " " + OpenTag + " ", " " + NewOpenTag);
			Markup = Strings.Replace(Markup, OpenTag, NewOpenTag);
			Markup = Strings.Replace(Markup, CloseTag, NewCloseTag);
			do
			{
				Markup = Strings.Replace(Markup, NewOpenTag + "\r\n", "\r\n" + NewOpenTag);
			}
			while (Strings.InStr(Markup, NewOpenTag + "\r\n") != 0);
			Markup = Strings.Replace(Markup, "\n" + NewOpenTag + " ", "\n" + NewOpenTag);
			Markup = Strings.Replace(Markup, " " + NewOpenTag + " \"", " " + NewOpenTag + "\"");
			Markup = Strings.Replace(Markup, NewOpenTag + " ", " " + NewOpenTag);
		}

		private void PreserveTex(ref string RTF)
		{
			colTex.Clear();
			RichTextBox richTextBox = new RichTextBox();
			try
			{
				richTextBox.Rtf = RTF;
			}
			catch (Exception ex)
			{
				ProjectData.SetProjectError(ex);
				Exception ex2 = ex;
				richTextBox.Text = RTF;
				ProjectData.ClearProjectError();
			}
			int num = 0;
			for (int num2 = richTextBox.Find("<TEX "); num2 > -1; num2 = richTextBox.Find("<TEX "))
			{
				int num3 = richTextBox.Find(" /TEX>");
				bool flag = false;
				try
				{
					if (richTextBox.Find(" /TEX>\r", num3, RichTextBoxFinds.None) == num3)
					{
						num3++;
						flag = true;
					}
				}
				catch (Exception ex3)
				{
					ProjectData.SetProjectError(ex3);
					Exception ex4 = ex3;
					ProjectData.ClearProjectError();
				}
				if (num3 <= num2)
				{
					break;
				}
				richTextBox.Select(num2, num3 - num2 + 6);
				string selectedText = richTextBox.SelectedText;
				if (Operators.CompareString(selectedText, "", TextCompare: false) != 0)
				{
					num++;
					selectedText = Strings.Mid(selectedText, 5);
					selectedText = ((!flag) ? Strings.Left(selectedText, Strings.Len(selectedText) - 5) : Strings.Left(selectedText, Strings.Len(selectedText) - 6));
					selectedText = selectedText.Trim();
					selectedText = Strings.Replace(selectedText, "\n", "[EOL!$]\r\n");
					if (flag)
					{
						selectedText += "[EOL!$]\r\n";
					}
					colTex.Add(selectedText);
					richTextBox.SelectedText = "<t!" + Conversions.ToString(num) + "!>";
				}
			}
			RTF = richTextBox.Rtf;
		}

		private void ParseTex(ref string RTF)
		{
			int count = colTex.Count;
			for (int i = 1; i <= count; i++)
			{
				string replacement = Conversions.ToString(colTex[i]);
				RTF = Strings.Replace(RTF, "<t!" + Conversions.ToString(i) + "!>", replacement);
			}
		}

		private bool IsEmptyChapter(clsProject cProject, clsChapter Ch)
		{
			bool flag = false;
			int sceneCount = Ch.SceneCount;
			for (int i = 1; i <= sceneCount; i++)
			{
				int iD = Ch.get_SceneIDByIndex(i);
				clsScene clsScene = cProject.get_SceneByID(iD);
				if (!clsScene.Unused)
				{
					if (!clsScene.ExportCondSpecific)
					{
						flag = true;
						break;
					}
					if (clsScene.ExportWhenLaTeX)
					{
						flag = true;
						break;
					}
				}
			}
			if (flag)
			{
				return false;
			}
			return true;
		}
	}
}
